﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WingMesLed
{
    public partial class LedItem : UserControl
    {
        public ModbusRTUDevice.NetDevice modbusTcp { get; private set; }
        bool LedLighting = false;
        TimeSpan WaitTime;
        DateTime LightStartTime = DateTime.Now;
       
        public LedItem(string ip)
        {
            InitializeComponent();
            modbusTcp = new ModbusRTUDevice.NetDevice(ip, 1030, 1, 400, 1000);
            modbusTcp.OutputCoils = new bool[2];
            modbusTcp.ReadCoilsLength = 2;
            modbusTcp.OnGetCoils += ModbusTcp_OnGetCoils;
            timer1.Start();
        }

        private void ModbusTcp_OnGetCoils(bool[] obj)
        {
            LedLighting = obj[0] && obj[1];
        }

        public void Begin()
        {
            modbusTcp.Begin();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            btnLedOff.Enabled = modbusTcp.Connected;
            btnLedOn.Enabled = modbusTcp.Connected;
            lbDeviceName.BackColor = modbusTcp.Connected ? Color.LightGreen : Color.Gray;
            LED.BackColor = LedLighting ? Color.Lime : Color.Gray;
            if (LedLighting)
            {
                WaitTime = DateTime.Now - LightStartTime;
            }
            else
            {
                LightStartTime = DateTime.Now;
                WaitTime = new TimeSpan(0);
            }
            lbWaitTime.Text = $"{WaitTime.Hours:D2}:{WaitTime.Minutes:D2}:{WaitTime.Seconds:D2}";
            lbWaitTime.ForeColor = WaitTime.TotalMinutes > 30 ? Color.Red : Color.Black;
        }

        private void btnLedOn_Click(object sender, EventArgs e)
        {
            modbusTcp.OutputCoils[0] = true;
            modbusTcp.OutputCoils[1] = true;
        }

        private void btnLedOff_Click(object sender, EventArgs e)
        {
            modbusTcp.OutputCoils[0] = false;
            modbusTcp.OutputCoils[1] = false;
        }
    }
}
